package com.sagereal.wtc.factorymode.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.R;

public class SpeakerActivity extends BaseActivity {
    private Button mTestPass,mTestFail;
    private MediaPlayer mMediaPlayer;
    private BroadcastReceiver mScreenReceiver,mHeadsetReceiver;
    private Handler mHandler;
    private Runnable mPlayRunnable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speaker);
        setTitle(getString(R.string.title_speaker_test));
        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        mHandler = new Handler();
        mPlayRunnable = this::startPlaying;

        initView();
        registerScreenReceiver();
//        registerHeadsetReceiver(); //在这里注册会出现息屏后拔出耳机播放的bug
    }

    private void initView() {
        //测试通过
        mTestPass.setOnClickListener(v -> {
            Intent intent = new Intent(SpeakerActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "pass");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
        //测试失败
        mTestFail.setOnClickListener(v -> {
            Intent intent = new Intent(SpeakerActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
        startPlaying();
    }

    private void startPlaying() {
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.sound); // 确保在 res/raw 文件夹中有一个 test_sound.mp3 文件
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Log.e("MediaPlayerError", "Error: what=" + what + ", extra=" + extra);
                return false;
            });
            mMediaPlayer.setOnPreparedListener(mp -> {
                Log.d("MediaPlayer", "MediaPlayer is prepared");
                mp.start();
            });
        } else if (!mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
        // 设置音量为最大
//        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
    }

    private void stopPlaying() {
        if (mMediaPlayer != null) {
            if(mMediaPlayer.isPlaying()){
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void registerScreenReceiver() {
        mScreenReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    mHandler.removeCallbacks(mPlayRunnable);
                    stopPlaying();
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    mHandler.post(mPlayRunnable);
                    startPlaying();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mScreenReceiver, filter);
    }

    private void registerHeadsetReceiver() {
        mHeadsetReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                    int state = intent.getIntExtra("state", -1);
                    switch (state) {
                        case 0:
                            /*耳机未插入*/
                            startPlaying();
                            mTestPass.setEnabled(true);
                            break;
                        case 1:
                            /*耳机插入*/
                            stopPlaying();
                            Toast.makeText(context, R.string.headset_out, Toast.LENGTH_SHORT).show();
                            mTestPass.setEnabled(false);
                            break;
                    }
                }
            }
        };

        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mHeadsetReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerHeadsetReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlaying();
        unregisterReceiver(mHeadsetReceiver);
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!hasFocus) {
            stopPlaying();
        } else {
            startPlaying();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScreenReceiver);
        stopPlaying();
    }
}